const express = require('express');

const router = express.Router();
//导入数据库操作模块
const db = require('../db/index');

//获取所有评论
router.post('/all', (req, res) => {
    const {goods_id} =req.body
    db.query(`select * from comment where goods_id=${goods_id}`, (err, result) => {
        if (err) {
            res.send({
                status: 500,
                message: '获取失败'
            })
        } else {
            res.send({
                status: 200,
                message: '获取成功',
                comments: result
            })
        }
    })
})


//插入
router.post('/insertComment', (req, res) => {
    const id = req.body.id;
    const content = req.body.content;
    const create_time = req.body.create_time;
    const user_id = req.body.user_id;
    const nickname = req.body.nickname;

    const comment = {
        user_id: user_id,
        content: content,
        create_time: create_time,
        nickname: nickname,
        goods_id: id
    }

    //插入评论
    db.query(`insert into comment set ?`, comment, (err, result) => {
        if (err) {
            console.log(err);
            res.json({
                code: 500,
                message: '服务器错误'
            });

        } else {
            res.json({
                code: 200,
                message: '评论成功'
            });
        }
    })

});

//删除评论
router.post('/deleteComment', (req, res) => {
    const id = req.body.id;
    //删除评论
    db.query(`delete from comment where id = ${id}`, (err, result) => {
        if (err) {
            res.json({
                code: 500,
                message: '服务器错误'
            });
        } else {
            res.json({
                code: 200,
                message: '删除成功'
            });
        }
    });
});

module.exports = router;